
const positionsModel = require('../models/positions')
const moment = require('moment')

const add = async (req, res, next) => {
  res.set('content-type', 'application/json;charset=utf-8')
  let result = await positionsModel.add({
    ...req.body,
    companyLogo: req.companyLogo,
    createTime: moment().format('YYYY-MM-DD hh:mm:ss a')
  })
  if(result) {

    process.socket.emit('message', 'ok');

    res.render('succ', {
      data: JSON.stringify({
        message: '职位添加成功！'
      })
    })
  } else {
    res.render('fail', {
      data: JSON.stringify({
        message: '职位添加失败。'
      })
    })
  }
}

const list = async (req, res, next) => {
  res.set('content-type', 'application/json;charset=utf-8')
  let list = await positionsModel.list()
  if(list && list.length) {
    res.render('succ', {
      data: JSON.stringify({
        list,
        message: '成功！'
      })
    })
  } else {
    res.render('fail', {
      data: JSON.stringify({
        message: '失败。'
      })
    })
  }
}

const remove = async (req, res, next) => {
  res.set('content-type', 'application/json;charset=utf-8')
  const { id } = req.body
  let result = await positionsModel.remove(id)
  console.log(result)
  try {
    if(result.deletedCount > 0) {
      res.render('succ', {
        data: JSON.stringify({
          message: '删除成功！'
        })
      })
    } else {
      res.render('fail', {
        data: JSON.stringify({
          message: '删除失败。'
        })
      })
    }
  } catch (err){
    res.render('fail', {
      data: JSON.stringify({
        message: '删除失败。'
      })
    })
  }
}

const update = async (req, res, next) => {
  res.set('content-type', 'application/json;charset=utf-8')

  const data = {
    ...req.body
  }
  if(req.companyLogo) {
    data['companyLogo'] = req.companyLogo
  } else {
    delete data['companyLogo'];
  }

  let result = await positionsModel.update(data)
  if(result) {
    res.render('succ', {
      data: JSON.stringify({
        message: '职位编辑成功！'
      })
    })
  } else {
    res.render('fail', {
      data: JSON.stringify({
        message: '职位编辑失败。'
      })
    })
  }
}
const listone = async (req, res, next) => {
  res.set('content-type', 'application/json;charset=utf-8')
  const { id } = req.query
  console.log(id)
  let result = await positionsModel.listone(id)
  console.log(result, 'listone')
  if(result) {
    res.render('succ', {
      data: JSON.stringify({
        result,
        message: '成功！'
      })
    })
  } else {
    res.render('fail', {
      data: JSON.stringify({
        message: '失败。'
      })
    })
  }
}

exports.add = add
exports.list = list
exports.remove = remove
exports.update = update
exports.listone = listone
